package com.demo.tool;


import com.demo.config.WkConfig;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.FilenameFilter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;

public class WkHtmlTool {

    /**
     *  返回 文件夹的html
     */
    public String listDirectory(  String uri, File f)   {
        String heading = "Directory " + uri;
        StringBuilder msg = new StringBuilder(
                "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"
                        + "<html xmlns=\"http://www.w3.org/1999/xhtml\">" + "<head>"
                        + "<meta content=\"text/html; charset=utf-8\" http-equiv=\"Content-Type\" />" + "<title>"
                        + heading + "</title>" + "<style type=\"text/css\">"
                        + "<!--H1 {font-family: Tahoma, Arial, sans-serif;color: white;background-color: #161616;font-size: 22px;}H2 {font-family: Tahoma, Arial, sans-serif;color: white;background-color: #525d76;font-size: 16px;}H3 {font-family: Tahoma, Arial, sans-serif;color: white;background-color: #525d76;font-size: 14px;}BODY {font-family: Tahoma, Arial, sans-serif;color: black;background-color: white;}B {font-family: Tahoma, Arial, sans-serif;color: white;background-color: #525d76;}P {font-family: Tahoma, Arial, sans-serif;background: white;color: black;font-size: 12px;}A {color: black;}A.name {color: black;}HR {color: #525d76;}-->"
                        + "</style>");
        do_buildJS(msg);
        msg.append("</head>");
        msg.append("<body><h1>").append(heading).append("</h1>");
        msg.append("<hr>");
        msg.append("<table><tr>");
        msg.append( "<td><input name=\"bt_fh\" type=\"button\" value=\"返回\" onclick=\"javascript:history.back();\" /></td>");
        msg.append("<td><form enctype=\"multipart/form-data\" name=\"fileul\" method=\"post\">");
        //msg.append("<input name=\"file\" type=\"file\" multiple=\"multiple\" />"); // 文件多选  multiple
        msg.append("<input name=\"file\" type=\"file\"   />");
        msg.append("<input name=\"btn_sc\" type=\"submit\" value=\"上传\"/>");
        msg.append("</form></td>");
        msg.append("<td><form name=\"xjwjj\" method=\"get\">");
        msg.append("<input type=\"text\" name=\"" + WkConfig.MKDIR + "\" />");
        msg.append("<input type=\"submit\" name=\"btn_xjwjj\" value=\"新建文件夹\" />  ");
        msg.append("</form></td>");


        msg.append("<td><input name=\"fhsy\" type=\"button\" value=\"返回首页\" onclick=\"location='/'\" /></td>");
        msg.append("</tr></table>");
        msg.append("<hr>");


        // 当前目录的上一级目录
        String upDir = null;
        if (uri.length() > 1) {
            String u = uri.substring(0, uri.length() - 1);  ;//[a ,b)
            int slash = u.lastIndexOf('/');
            if (slash >= 0 && slash < u.length()) {
                upDir = uri.substring(0, slash + 1);
            }
        }


        List<String> files = Arrays.asList( f.list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                // 显示文件夹下的 所有文件（不包括文件夹）
                return new File(dir, name).isFile();
            }
        }));

        Collections.sort(files);//使用默认的正序排序

        List<String> directories = Arrays.asList(f.list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                // 过滤所有文件夹
                return new File(dir, name).isDirectory();
            }
        }));
        Collections.sort(directories);


        msg.append(
                "<table border=0 width=\"100%\" cellspacing=\"0\" cellpadding=\"5\" align=\"center\" style=\"overflow: scroll;word-break: keep-all\">"
                        + "<tr bgcolor=\"#3b9bff\">" + "<td width=\"5%\">序号</td>" + "<td width=\"30%\">文件名</td>"
                        + "<td width=\"15%\">文件大小</td>" + "<td  width=\"25%\">文件修改时间</td>"
                        + "<td align=\"center\">MD5</td>" + "<td width=\"5%\">操作</td>" + "</tr>");

        int xxxidn = 1;
        String xxxName = "";
        String xxxSize = "";
        String xxxModifyTime = "";
        String xxxGetMD5 = "";
        String xxxIsDel = "";

        if (upDir != null) {
            // 第一行，返回父目录的
            xxxName = "..";
            msg.append("<tr>");
            msg.append("<td>").append(xxxidn++).append("</td>");
            msg.append( "<td><a rel=\"directory\" href=\"").append(encodeUri(upDir)) .append("\"><span>" + xxxName + "</span></a></td>" + "<td>" + xxxSize + "</td><td>"
                    + xxxModifyTime + "</td><td>" + xxxGetMD5 + "</td><td>" + xxxIsDel + "</td></tr>");
        }


        for (String directory : directories) {
            if (xxxidn % 2 != 0) {
                msg.append("<tr>");
            } else {
                msg.append("<tr bgcolor=\"#fffae3\">");
            }
            msg.append("<td>").append(xxxidn++).append("</td>");

            xxxName = directory + "/";
            xxxIsDel = "<a style=\"background-color: #ceffce;\"  href=\"?delete=" + encodeUri(xxxName)+ "\" onclick=\"return confirm('请确认是否删除:" + xxxName + "?');\">删除</a>";

            String msgg ="<td><a rel=\"directory\" href=\""+encodeUri(xxxName) +"\"><span style=\"background-color: #ceffce;\">"+xxxName+"</span></a></td>" + "<td>" + xxxSize + "</td><td>" + xxxModifyTime + "</td><td>"
                    + xxxGetMD5 + "</td><td>" + xxxIsDel + "</td></tr>";
            msg.append(msgg) ;
        }


        for (String file : files) {
            xxxName = file;
            if (xxxidn % 2 != 0) {
                msg.append("<tr>");
            } else {
                msg.append("<tr bgcolor=\"#eeeeee\">");
            }
            msg.append("<td>").append(xxxidn).append("</td>");
            msg.append("<td><a href=\"").append(encodeUri(xxxName)).append("\"><span>").append(xxxName) 	.append("</span></a>");

            File curFile = new File(f, xxxName);
            long fileSize = FileUtils.sizeOf(curFile);
            xxxSize = FileUtils.byteCountToDisplaySize(fileSize) + "";

            xxxModifyTime = " ---- "  ;
            xxxGetMD5 = " ---- "  ;
            xxxIsDel = "<a style=\"background-color: #ceffce;\"  href=\"?delete=" + encodeUri(xxxName) 	+ "\" onclick=\"return confirm('请确认是否删除:" + xxxName + "?');\">删除</a>";

            msg.append("</td>" + "<td>" + xxxSize + "</td><td>" + xxxModifyTime + "</td><td align=\"center\">" + xxxGetMD5 + "</td><td>" + xxxIsDel + "</td></tr>");
            xxxidn++;
        }


        msg.append("</table>\n<hr>\n  \n</body>\n</html>\n");
        return msg.toString();
    }

    public void do_buildJS(StringBuilder msg) {
        msg.append("<script type=\"text/javascript\">");
        msg.append("function callBackMD5(murl,domId){\r\n"
                + "http.get({url:murl,timeout:100000},function(err,result){document.getElementById(domId).innerHTML=result;});\r\n"
                + "}");
        msg.append("var http = {};\n");
        msg.append("http.quest = function (option, callback) {\n");
        msg.append("    var url = option.url;\n");
        msg.append("    var method = option.method;\n");
        msg.append("    var data = option.data;\n");
        msg.append("    var timeout = option.timeout || 0;\n");
        msg.append("    var xhr = new XMLHttpRequest();\n");
        msg.append("    (timeout > 0) && (xhr.timeout = timeout);\n");
        msg.append("    xhr.onreadystatechange = function () {\n");
        msg.append("        if (xhr.readyState == 4) {\n");
        msg.append("            if (xhr.status >= 200 && xhr.status < 400) {\n");
        msg.append("            var result = xhr.responseText;\n");
        msg.append("            try {result = JSON.parse(xhr.responseText);} catch (e) {}\n");
        msg.append("                callback && callback(null, result);\n");
        msg.append("            } else {\n");
        msg.append("                callback && callback('status: ' + xhr.status);\n");
        msg.append("            }\n");
        msg.append("        }\n");
        msg.append("    }.bind(this);\n");
        msg.append("    xhr.open(method, url, true);\n");
        msg.append("    if(typeof data === 'object'){\n");
        msg.append("        try{\n");
        msg.append("            data = JSON.stringify(data);\n");
        msg.append("        }catch(e){}\n");
        msg.append("    }\n");
        msg.append("    xhr.send(data);\n");
        msg.append("    xhr.ontimeout = function () {\n");
        msg.append("        callback && callback('timeout');\n");
        msg.append(
                "        console.log('%c连%c接%c超%c时', 'color:red', 'color:orange', 'color:purple', 'color:green');\n");
        msg.append("    };\n");
        msg.append("};\n");
        msg.append("http.get = function (url, callback) {\n");
        msg.append("    var option = url.url ? url : { url: url };\n");
        msg.append("    option.method = 'get';\n");
        msg.append("    this.quest(option, callback);\n");
        msg.append("};\n");
        msg.append("http.post = function (option, callback) {\n");
        msg.append("    option.method = 'post';\n");
        msg.append("    this.quest(option, callback);\n");
        msg.append("};\n");
        msg.append("</script>");
    }


    /**
     * URL-encodes everything between "/"-characters. Encodes spaces as '%20'
     * instead of '+'.
     */
    private String encodeUri(String uri) {
        String newUri = "";
        StringTokenizer st = new StringTokenizer(uri, "/ ", true);
        while (st.hasMoreTokens()) {
            String tok = st.nextToken();
            if ("/".equals(tok)) {
                newUri += "/";
            } else if (" ".equals(tok)) {
                newUri += "%20";
            } else {
                try {
                    newUri += URLEncoder.encode(tok, "UTF-8");
                } catch (UnsupportedEncodingException ignored) {
                    ignored.printStackTrace();
                }
            }
        }
        return newUri;
    }

}
